package com.service.purchase;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import com.alibaba.excel.EasyExcel;
import com.common.StringUtils;
import com.common.easyui.EasyuiUtils;
import com.common.http.HttpResult;
import com.common.http.HttpStatus;
import com.common.model.Global;
import com.common.spring.SpringMvcUtils;
import com.dao.purchase.PurchaseSixCostsOrdersDao;
import com.dao.purchase.PurchaseSixCostsOrdersLinesDao;
import com.dao.sale.SaleDeliveryOrdersDao;
import com.dao.sys.SysDictMapper;
import com.model.purchase.PurchaseSixCostsOrdersLinesModel;
import com.model.purchase.PurchaseSixCostsOrdersModel;
import com.model.sale.SaleDeliveryOrdersModel;
import com.model.sys.SysDict;
import com.model.sys.SysUser;
import com.service.external.sap.SapPurchaseService;

@Service
public class PurchaseSixCostsOrdersService {
	static final Logger logger = LoggerFactory.getLogger(PurchaseSixCostsOrdersService.class);

	@Autowired
	PurchaseSixCostsOrdersDao sixCostsOrdersDao;

	@Autowired
	PurchaseSixCostsOrdersLinesDao sixCostsOrdersLinesDao;

	@Autowired
	SysDictMapper sysDictMapper;

	@Autowired
	SapPurchaseService sapPurchaseService;

	@Autowired
	SaleDeliveryOrdersDao deliveryOrdersDao;

	/**
	 * 列表查询
	 *
	 * @param queryMap
	 * @return
	 */
	public HttpResult selectList(Map<String, Object> queryMap) {
		HttpResult httpResult = new HttpResult();
		EasyuiUtils.addPageNum(queryMap);
		EasyuiUtils.addFilter(queryMap);
		SysUser sysUser = SpringMvcUtils.getSysUser();
		if (!sysUser.getSuperadmin().equals(Global.YES + "")) {
			if (StringUtils.isNotNull(sysUser.getDatapermission())) {
				queryMap.put("deptIds", sysUser.getDatapermission().split(","));
			} else {
				queryMap.put("createId", sysUser.getUserid());
			}
		}
		List<PurchaseSixCostsOrdersModel> list = sixCostsOrdersDao.selectList(queryMap);
		int count = sixCostsOrdersDao.selectListCount(queryMap);
		httpResult.setRows(list);
		httpResult.setTotal(count);
		logger.info("selectList:{}", list);
		return httpResult;
	}

	/**
	 * 详情
	 *
	 * @param
	 * @return
	 */
	public HttpResult selectInfor(String purId) {
		HttpResult httpResult = new HttpResult();
		PurchaseSixCostsOrdersModel sixCostsOrdersModel = sixCostsOrdersDao.load(purId);
		if (sixCostsOrdersModel != null) {
			Map<String, Object> params = new HashMap<>();
			params.put("purId", purId);
			List<PurchaseSixCostsOrdersLinesModel> lines = sixCostsOrdersLinesDao.selectList(params);
			sixCostsOrdersModel.setPurchaseSixCostsOrdersLines(lines);
		}

		httpResult.setData(sixCostsOrdersModel);
		httpResult.setCode(HttpStatus.SUCCESS_CODE);
		return httpResult;
	}

	/**
	 * 保存
	 *
	 * @param
	 * @return
	 */
	@Transactional
	public HttpResult save(PurchaseSixCostsOrdersModel sixCostsOrdersModel) {
		if (sixCostsOrdersModel == null) {
			return HttpResult.error("参数不能为空");
		}
		// 判断该purId状态是否为已提交，防止重复生产采购订单
		if (!StringUtils.isNullOrEmpty(sixCostsOrdersModel.getPurId())) {
			PurchaseSixCostsOrdersModel sixCostsOrdersTemp = sixCostsOrdersDao.load(sixCostsOrdersModel.getPurId());
			if ((Global.YES + "").equals(sixCostsOrdersTemp.getStatus())) {
				return HttpResult.error("该条数据已提交，请勿重复操作!");
			}
		}
		String msg = "";
		List<PurchaseSixCostsOrdersLinesModel> sixCostsOrdersLines = sixCostsOrdersModel
				.getPurchaseSixCostsOrdersLines();
		if (CollectionUtils.isEmpty(sixCostsOrdersLines)) {
			return HttpResult.error("费用行项目不能为空!");
		}
		HttpResult httpResult = new HttpResult();
		int result = 0;
		if (StringUtils.isNullOrEmpty(sixCostsOrdersModel.getFactoryCode())) {
			return HttpResult.error("工厂代码不得为空!");
		}
		// 根据工厂代码查询公司代码
		Map<String, String> dictParam = new HashMap<>();
		dictParam.put("remark", sixCostsOrdersModel.getFactoryCode());
		dictParam.put("dicName", "公司代码");
		SysDict dict = sysDictMapper.selectByDicNameAndRemark(dictParam);
		if (dict != null) {
			sixCostsOrdersModel.setCompanyCode(dict.getDicValue());
		} else {
			return HttpResult.error("未查询到公司代码!");
		}
		// 费用采购类型
		String costType = sixCostsOrdersModel.getCostType();
		/**
		 * status =1
		 */
		// 调用SAP接口，生成采购订单,返回订单号
		if (sixCostsOrdersModel.getStatus().equals(Global.YES + "")) {
			HttpResult sapHttpResult = sapPurchaseService.createSapSixCostsOrder(sixCostsOrdersModel);
			if (sapHttpResult.getCode() == HttpStatus.SUCCESS_CODE) {
				// 保存采购订单号
				sixCostsOrdersModel.setSapOrderNo(sapHttpResult.getData().toString());
				msg = sapHttpResult.getMsg();
			} else {
				logger.error(sapHttpResult.getMsg());
				return HttpResult.error(sapHttpResult.getMsg());
			}
		}
		/**
		 * 头表信息
		 */
		if (!StringUtils.isNotNull(sixCostsOrdersModel.getPurId())) {
			sixCostsOrdersModel.setPurId(UUID.randomUUID().toString());
			result = sixCostsOrdersDao.insert(sixCostsOrdersModel);
		} else {
			result = sixCostsOrdersDao.update(sixCostsOrdersModel);
		}
		/**
		 * 行表信息操作
		 */
		// 先删除行信息
		sixCostsOrdersLinesDao.deleteByPurId(sixCostsOrdersModel.getPurId());
		for (PurchaseSixCostsOrdersLinesModel sixCostsOrdersLinesModel : sixCostsOrdersLines) {
			// 提交时，更新交货单的对应费用状态
			if (sixCostsOrdersModel.getStatus().equals(Global.YES + "")) {
				SaleDeliveryOrdersModel deliveryOrdersModel = new SaleDeliveryOrdersModel();
				// 交货单号
				deliveryOrdersModel.setOrderNo(sixCostsOrdersLinesModel.getDeliveryNo());
				if ("YJ".equals(costType)) {
					deliveryOrdersModel.setBrokerageEnd("1");
				} else if ("GZF".equals(costType)) {
					deliveryOrdersModel.setPortSurchargeEnd("1");
				} else if ("BXF".equals(costType)) {
					deliveryOrdersModel.setPremiumEnd("1");
				} else if ("BGF".equals(costType)) {
					deliveryOrdersModel.setCustomsEnd("1");
				} else if ("BJF".equals(costType)) {
					deliveryOrdersModel.setCostomsCensoringChargesEnd("1");
				} else if ("JYF".equals(costType)) {
					deliveryOrdersModel.setSurrveyFeesEnd("1");
				}
				// 更新交货单费用完成状态
				deliveryOrdersDao.update(deliveryOrdersModel);
			}
			// 设置采购订单号
			sixCostsOrdersLinesModel.setSapOrderNo(sixCostsOrdersModel.getSapOrderNo());

			sixCostsOrdersLinesModel.setLineId(UUID.randomUUID().toString());
			sixCostsOrdersLinesModel.setPurId(sixCostsOrdersModel.getPurId());
			// 新增行信息
			result += sixCostsOrdersLinesDao.insert(sixCostsOrdersLinesModel);
		}

		if (result > 0) {
			httpResult.setMsg(sixCostsOrdersModel.getStatus().equals(Global.YES + "") ? "提交成功!" : "保存成功!" + msg);
			httpResult.setData(sixCostsOrdersModel);
		} else {
			httpResult.setCode(HttpStatus.GLOBAL_EXCEPTION_CODE);
			httpResult.setMsg(sixCostsOrdersModel.getStatus().equals(Global.YES + "") ? "提交失败!" : "保存失败!" + msg);
		}
		return httpResult;
	}

	/**
	 * 提交
	 *
	 * @param
	 * @return
	 */
	public HttpResult commit(PurchaseSixCostsOrdersModel sixCostsOrdersModel) {
		if (sixCostsOrdersModel == null) {
			return HttpResult.error("参数不能为空");
		}
		sixCostsOrdersModel.setStatus(Global.YES + "");
		HttpResult httpResult = new HttpResult();
		int result = 0;
		result = sixCostsOrdersDao.update(sixCostsOrdersModel);
		if (result > 0) {
			httpResult.setMsg(sixCostsOrdersModel.getStatus().equals(Global.YES + "") ? "提交成功!" : "保存成功!");
			httpResult.setData(sixCostsOrdersModel);
		} else {
			httpResult.setCode(HttpStatus.GLOBAL_EXCEPTION_CODE);
			httpResult.setMsg(sixCostsOrdersModel.getStatus().equals(Global.YES + "") ? "提交失败!" : "保存失败!");
		}
		return httpResult;
	}

	/**
	 * 删除
	 *
	 * @param
	 * @return
	 */
	public HttpResult delete(String purId) {
		if (!StringUtils.isNotNull(purId)) {
			return HttpResult.error("参数不能为空");
		}
		PurchaseSixCostsOrdersModel model = sixCostsOrdersDao.load(purId);
		if (!model.getStatus().equals(Global.NO + "")) {
			return HttpResult.error("已提交，不可删除！");
		}
		HttpResult httpResult = new HttpResult();
		int result = sixCostsOrdersDao.delete(purId);

		if (result > 0) {
			// 删除后，将对应费用类型的交货单置为可选
			String costType = model.getCostType();
			Map par = new HashMap();
			par.put("purId", purId);
			List<PurchaseSixCostsOrdersLinesModel> lines = sixCostsOrdersLinesDao.selectList(par);
			if (!CollectionUtils.isEmpty(lines)) {
				for (PurchaseSixCostsOrdersLinesModel sixCostsOrdersLinesModel : lines) {
					par.clear();
					par.put("costType", costType);
					par.put("deliveryNo", sixCostsOrdersLinesModel.getDeliveryNo());
					par.put("status", "0");
					updateDeliveryOrdersStatus(par);
				}
			}
			httpResult.setMsg("删除成功！");
		} else {
			httpResult.setCode(HttpStatus.GLOBAL_EXCEPTION_CODE);
			httpResult.setMsg("不存在此条数据！");
		}
		return httpResult;
	}

	/**
	 * 撤回
	 *
	 * @param
	 * @return
	 */
	public HttpResult back(String purId) {
		if (!StringUtils.isNotNull(purId)) {
			return HttpResult.error("参数不能为空");
		}
		PurchaseSixCostsOrdersModel model = sixCostsOrdersDao.load(purId);

		// todo

		HttpResult httpResult = new HttpResult();
		model.setStatus(Global.NO + "");
		int result = sixCostsOrdersDao.update(model);
		if (result > 0) {
			httpResult.setMsg("删除成功！");
		} else {
			httpResult.setCode(HttpStatus.GLOBAL_EXCEPTION_CODE);
			httpResult.setMsg("不存在此条数据！");
		}
		return httpResult;
	}

	/**
	 * 导出
	 *
	 * @param queryMap
	 * @param response
	 */
	public void export(Map<String, Object> queryMap, HttpServletResponse response) {
		List<PurchaseSixCostsOrdersModel> list = sixCostsOrdersDao.selectList(queryMap);
		logger.info("export:{}", list);
		try {
			EasyExcel.write(response.getOutputStream(), PurchaseSixCostsOrdersModel.class).sheet("模板").doWrite(list);
		} catch (IOException e) {
			logger.error("导出错误:{}", e.getMessage());
		}

	}

	// 更新交货单状态
	public HttpResult updateDeliveryOrdersStatus(Map<String, String> queryMap) {
		HttpResult httpResult = new HttpResult();
		String costType = queryMap.get("costType");
		String status = queryMap.get("status");
		if (StringUtils.isNullOrEmpty(costType)) {
			return HttpResult.error("费用类型不得为空");
		}
		String deliveryNo = queryMap.get("deliveryNo");
		if (StringUtils.isNullOrEmpty(deliveryNo)) {
			return HttpResult.error("交货单号不得为空");
		}
		if (StringUtils.isNullOrEmpty(status)) {
			return HttpResult.error("状态不得为空");
		}
		SaleDeliveryOrdersModel deliveryOrdersModel = new SaleDeliveryOrdersModel();
		deliveryOrdersModel.setOrderNo(deliveryNo);
		// 佣金
		if ((costType).equals("YJ")) {
			deliveryOrdersModel.setBrokerageEnd(status);
		} // FOB港杂费
		if ((costType).equals("GZF")) {
			deliveryOrdersModel.setPortSurchargeEnd(status);

		} // 保险费
		if ((costType).equals("BXF")) {
			deliveryOrdersModel.setPremiumEnd(status);

		} // 查验费
		if ((costType).equals("JYF")) {
			deliveryOrdersModel.setSurrveyFeesEnd(status);

		} // 报检费
		if ((costType).equals("BJF")) {
			deliveryOrdersModel.setCostomsCensoringChargesEnd(status);
		} // 报关费
		if ((costType).equals("BGF")) {
			deliveryOrdersModel.setCustomsEnd(status);
		}
		int i = deliveryOrdersDao.update(deliveryOrdersModel);
		if (i > 0) {
			httpResult.setMsg("修改成功");
		} else {
			httpResult.setCode(HttpStatus.GLOBAL_EXCEPTION_CODE);
			httpResult.setMsg("修改失败！");
		}
		return httpResult;

	}
}
